<?php
namespace Home\Controller;
use Common\Controller\FirstendController;

import("ITK.Itklib.itaoke_https");
import("ITK.ORG.Pinyin");
class ItemController extends FirstendController 
{
    public function _initialize()
    {
        parent::_initialize();
        $this->_mod = D('Items');
        $this->_tagmod = D('Tags');
        $this->_cate_mod = D('ItemsCate');
        $this->assign('nav_curr', 'index');
        if (!$this->visitor->is_login && in_array(ACTION_NAME, array('delete', 'comment', 'delcol', 'mycol'))) {
            IS_AJAX && $this->ajaxReturn(0, L('login_please'));
            $this->redirect('User/login');
        }
        if (C('itk_site_cache')) {
            $file = 'items_site';
        }
    }
    public function index()
    {
        $id = I('id', '', 'trim');
        $iid = I('iid', '', 'trim');
        if ($id) {
            $item = $this->_mod->where(array('id' => $id))->find();
        } else {
            $item = $this->_mod->where(array('num_iid' => $iid))->find();
        }
        !$item && $this->_404();
        $item['class'] = $this->_mod->status($item['status'], $item['coupon_start_time'], $item['coupon_end_time']);
        $txurl = C('itk_site_url') . U('Item/index', array('id' => $item['id']));
        $item['txurl'] = urlencode($txurl);
        $item['zk'] = round($item['coupon_price'] / $item['price'] * 10, 2);
        $item['iurl'] = C('itk_site_url') . '/item/' . $item['id'] . '.html';
        $item['jurl'] = C('itk_site_url') . '/jump/' . $item['id'] . '.html';
        $item['ccid'] = $item['cate_id'];
        if (isset($item['cate_id'])) {
            $item['cname'] = D('ItemsCate')->where(array('id' => $item['cate_id']))->getField('name');
        }
        $iid = $item['num_iid'];
        $this->assign('id',$item['id']);
        $this->assign('num_iid',$item['num_iid']);
        
        $whoids_list = D('ItemsLike')->field('id,uid')->limit(0, 6)->where(array('num_iid' => $iid))->order('id desc')->select();
        $wholike = D('ItemsLike')->where(array('num_iid' => $iid))->count();
        $whoids = array();
        if ($whoids_list) {
            foreach ($whoids_list as $v) {
                $whoids[] = $v['uid'];
            }
        }
        $this->getTodayRank();
        
        if($whoids)
        {
        	$who['id'] = array('in', $whoids);
        	$who_list = D('User')->field('id,username,email,qq,last_time')->where($who)->select();
        	foreach ($who_list as $key => $vs) {
        		$whos[$key] = $vs;
        	}
        	$this->assign('whos', $whos);
        }

        $this->assign('wholike', $wholike);
        if (C('itk_item_hit')) {
            $hits_data = array('hits' => array('exp', 'hits+1'));
            $this->_mod->where(array('id' => $id))->setField($hits_data);
        }
        $cate_data = F('cate_list');
        $cid = $item['cate_id'];
        $pid = $cate_data[$cid]['pid'];
        
        // tags 处理
        if($item['tags'] == '')
        {
        	$tag_list = D('Items')->get_tags_by_title($item['title']);
        	$tags = implode(',', $tag_list);
        	if (C('itk_tag_auto') == 1) {
        		$autonum = C('itk_tag_auto_num');
        		$pinyin = new \Pinyin();
        		$etag = $pinyin->getAllPY($tags);
        		$etag = explode(',', $etag);
        		$ztag = explode(',', $tags);
        		for ($i = 0; $i < $autonum; $i++) {
        			$items['ename'] = $etag[$i];
        			$items['ename'] = str_replace(' ', '', $items['ename']);
        			$items['name'] = $ztag[$i];
        			if (!$this->_tagmod->where(array('ename' => $items['ename']))->count()) {
        				$this->_tagmod->add($items);
        			}
        		}
        	}   
        	//更新主表
        	$_d['tags']=$tags;
        	M('Items')->where(array("id"=>$item['id']))->save($_d);
        }
		else {
			$tags = explode(',', $item['tags']);
		}

		$this->assign('tags',$tags);
        $this->_config_seo(C('itk_seo_config.item'), array('title' => $item['title'], 'intro' => $item['intro'], 'price' => $item['price'], 'coupon_price' => $item['coupon_price'], 'tags' => $tags, 'seo_title' => $item['seo_title'], 'seo_keywords' => $item['seo_keys'], 'seo_description' => $item['seo_desc']));
      
        if (false === ($cate_list = F('cate_list'))) {
            $cate_list = D('ItemsCate')->cate_cache();
        }
        if (C('itk_site_cache')) {
            $file = 'orlike_' . $cid;
            if (false === ($orlike = S($file))) {
                if ($cid) {
                    $orlike = $this->_mod->where(array('cate_id' => $cid, 'isshow' => '1', 'pass' => '1'))->limit('0,12')->order('id desc')->select();
                } else {
                    $orlike = $this->_mod->where(array('isshow' => '1', 'pass' => '1'))->limit('0,12')->order('id desc')->select();
                }
                S($file, $orlike);
            }
        } else {
            if ($cid) {
                $orlike = $this->_mod->where(array('cate_id' => $cid, 'isshow' => '1', 'pass' => '1'))->limit('0,12')->order('id desc')->select();
            } else {
                $orlike = $this->_mod->where(array('isshow' => '1', 'pass' => '1'))->limit('0,12')->order('id desc')->select();
            }
        }
        $items = array();
        $pagecount = 0;
        $seller_arr = array();
        $sellers = '';
        foreach ($orlike as $key => $val) {
            $items[$key] = $val;
            $items[$key]['class'] = $this->_mod->status($val['status'], $val['coupon_start_time'], $val['coupon_end_time']);
            $items[$key]['pics'] = $this->pic = D('items')->where(array('id' => $item['id']))->getField('pic_url');
            $items[$key]['titles'] = $this->title = D('items')->where(array('id' => $item['id']))->getField('title');
            $items[$key]['zk'] = round($val['coupon_price'] / $val['price'] * 10, 1);
            $items[$key]['itemurl'] = C('itk_site_url') . '/item/' . $val['id'] . '.html';
            $items[$key]['jumpurl'] = C('itk_site_url') . '/jump/' . $val['id'] . '.html';
            if (!$val['click_url']) {
                $items[$key]['click_url'] = U('jump/index', array('id' => $val['id']));
            }
            if ($val['coupon_start_time'] > time()) {
                $items[$key]['click_url'] = U('item/index', array('id' => $val['id']));
                $items[$key]['timeleft'] = $val['coupon_start_time'] - time();
            } else {
                $items[$key]['timeleft'] = $val['coupon_end_time'] - time();
            }
            $items[$key]['cate_name'] = $cate_list['p'][$val['cate_id']]['name'];
            $url = C('itk_site_url') . U('item/index', array('id' => $val['id']));
            $items[$key]['url'] = urlencode($url);
            $items[$key]['urltitle'] = urlencode($val['title']);
            $items[$key]['price'] = number_format($val['price'], 1);
            $items[$key]['coupon_price'] = number_format($val['coupon_price'], 1);
            $pagecount++;
            if ($val['sellerId']) {
                $seller_arr[] = $val['sellerId'];
            }
        }
        $seller_arr = array_unique($seller_arr);
        $sellers = implode(',', $seller_arr);
        $this->assign('sellers', $sellers);
        $this->assign('items_list', $items);
        $this->assign('cate_list', $cate_list);
        $nodesc=0;		// 默认有desc
    	if (!$item['desc']) {
			$infoUrl = 'http://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?data=%7B%22item_num_id%22%3A%22' . $item['num_iid'] . '%22%7D';
			$itaoke_https = new \itaoke_https();
			$itaoke_https->fetch($infoUrl);
			$source = $itaoke_https->results;
			$comlist = json_decode($source, true);
			$isGetDesc = false;
			if(is_array($comlist)){
				if($comlist[ret][0]=='SUCCESS::接口调用成功'){
					$isGetDesc=true;
				}
			}
			if (!$isGetDesc) {
				$UserAgent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
				$curl = curl_init();
				curl_setopt($curl, CURLOPT_URL, $infoUrl);
				curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
				curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
				curl_setopt($curl, CURLOPT_HEADER, 0);
				curl_setopt($curl, CURLOPT_USERAGENT, $UserAgent);
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
				$data = curl_exec($curl);
				$comlist = json_decode($data, true);
				if(is_array($comlist)){
					if($comlist[ret][0]=='SUCCESS::接口调用成功'){
						$isGetDesc=true;
					}
				}
			}

			if($isGetDesc){
				$tm = $comlist['data']['images'];
				$onepic = '<img class="lazy" src=' . $tm[0] . '>';
				$item['desc'] = implode('', $tm);
				foreach ($tm as $sms) {
					if (strpos($item['desc'], $sms)) {
						$imgurl = '<img class="lazy" src=' . $sms . '>';
						$item['desc'] = str_replace($sms, $imgurl, $item['desc']);
						$item['desc'] = str_replace($tm[0], '', $item['desc']);
					}
				}
				$item['desc'] = $onepic . '' . $item['desc'];
				$_data['desc'] = $item['desc'];
				$this->_mod->where(array('id' => $id))->save($_data);
			}else{
				$nodesc=1;		// 无详情获取不到了
			}
		}
		else
		{
			$item['desc']=htmlspecialchars_decode($item['desc']);
		}
		
		$this->assign('nodesc',$nodesc);
        $desc = $item['desc'];

        if($item['click_url']){
        	$this->assign('hUrl',$item['click_url']);
        }else{
        	if($item['isq']==1)
        		$this->getUtao($item['id'],$item['num_iid'],$item['quanurl'],$item['dx']);
        }
        
        $this->assign('info', $info);
        $this->assign('item', $item);
        $this->assign('desc', $desc);
        $this->display();
    }
    public function comment_list()
    {
        $id = I('id', '', 'intval');
        !$id && $this->ajaxReturn(0, L('invalid_item'));
        $item = $this->_mod->where(array('id' => $id, 'pass' => '1'))->count('id');
        !$item && $this->ajaxReturn(0, L('invalid_item'));
        $item_comment_mod = M('ItemsComment');
        $pagesize = 8;
        $map = array('item_id' => $id, 'status' => '1');
        $count = $item_comment_mod->where($map)->count('id');
        $pager = $this->_pager($count, $pagesize);
        $pager->listRows = 8;
        $cmt_list = $item_comment_mod->where($map)->order('add_time DESC')->limit($pager->firstRow . ',' . $pager->listRows)->select();
        $this->assign('cmt_list', $cmt_list);
        $data = array();
        $data['list'] = $this->fetch('comment_list');
        $data['page'] = $pager->fshow();
        $this->ajaxReturn(1, '', $data);
    }
    
    /**
     * 查询今日排行榜
     */
    private function getTodayRank()
    {
    	$where['add_time'] =array('GT',strtotime(date('Y-m-d', time())));
    	$where['isq']=1;
    	$res = M('Items')->where($where)->order("volume desc")->limit(5)->select();
    	$this->assign('trank',$res);
    	$this->getRandomQuan();
    }
   
    /**
     * 随机12个相关的信息
     */
    private function getRandomQuan()
    {
 //   	$_pre=C('DB_PREFIX');
 //   	$res =M()->query("SELECT * FROM {$_pre}items AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM {$_pre}items )-(SELECT MIN(id) FROM {$_pre}items ))+(SELECT MIN(id) FROM {$_pre}items )) AS id) AS t2 WHERE t1.id >= t2.id and t1.isq =1 and t1.coupon_end_time < unix_timestamp(now()) ORDER BY t1.id LIMIT 8");
 //   	$this->assign('random',$res);
    	
    	$items = M('Items');
    	$num=12;
    	$where['isq']=1;
    	$where['status']='underway';
    	$countcus=$items->where($where)->count();
    	
    	if($countcus==0){
    		unset($where['cate_id']);
    		$countcus=$items->where($where)->count();
    	}
    	$res=array();
    	$min=$items->where($where)->min('id');
    	$max=$items->where($where)->max('id');
    	if($countcus<$num){
    		$num=$countcus;
    	}
    	$i=1;
    	$flag=0;
    	while($i<=$num){
    		$rundnum=rand($min, $max);
    		if($flag!=$rundnum){
    			if($addlink=$items->getById($rundnum) ){
    				$res[]=$addlink;
    				$flag=$rundnum;
    				$i++;
    			}
    		}
    	}
    	$this->assign('random',$res);
    }
    
    public function comment()
    {
        foreach ($_POST as $key => $val) {
            $_POST[$key] = \Input::deleteHtmlTags($val);
        }
        $data = array();
        $data['item_id'] = I('id', '', 'intval');
        !$data['item_id'] && $this->ajaxReturn(0, L('invalid_item'));
        $data['info'] = I('content', '', 'trim');
        !$data['info'] && $this->ajaxReturn(0, L('please_input') . L('comment_content'));
        $data['status'] = 1;
        $data['uid'] = $this->visitor->info['id'];
        $data['uname'] = $this->visitor->info['username'];
        $item = $this->_mod->field('id,uid,nick')->where(array('id' => $data['item_id'], 'pass' => '1'))->find();
        !$item && $this->ajaxReturn(0, L('invalid_item'));
        $item_comment_mod = D('ItemsComment');
        if (false === $item_comment_mod->create($data)) {
            $this->ajaxReturn(0, $item_comment_mod->getError());
        }
        $comment_id = $item_comment_mod->add();
        if ($comment_id) {
            $this->assign('cmt_list', array(array('uid' => $data['uid'], 'uname' => $data['uname'], 'info' => $data['info'], 'add_time' => time())));
            $resp = $this->fetch('comment_list');
            $this->ajaxReturn(1, L('comment_success'), $resp);
        } else {
            $this->ajaxReturn(0, L('comment_failed'));
        }
    }
    public function noshow()
    {
        $id = I('id');
        $username = $this->visitor->info['username'];
        if ($username != C('itk_index_admin')) {
            $this->ajaxReturn(0, '越权！');
        }
        $data['isshow'] = 0;
        if (M('items')->where(array('num_iid' => $id))->save($data)) {
            $this->ajaxReturn(1, '取消成功！');
        } else {
            $this->ajaxReturn(0, $this->_mod->getError());
        }
    }
    public function delete()
    {
        $id = I('id', '', 'intval');
        !$id && $this->ajaxReturn(0, L('invalid_item'));
        $uid = $this->visitor->info['id'];
        $uname = $this->visitor->info['username'];
        $result = D('Items')->where(array('id' => $id))->delete();
        if ($result) {
            $this->ajaxReturn(1, L('del_item_success'));
        } else {
            $this->ajaxReturn(0, L('del_item_failed'));
        }
    }
    public function _empty()
    {
        header('HTTP/1.0 404 Not Found');
        $this->display('Public:404');
    }
    public function ajax_getchilds()
    {
        $id = I('id', '', 'intval');
        $map = array('pid' => $id, 'status' => '1');
        $return = M('ItemsCate')->field('id,name')->where($map)->select();
        if ($return) {
            $this->ajaxReturn(1, L('operation_success'), $return);
        } else {
            $this->ajaxReturn(0, L('operation_failure'));
        }
    }
    
    /**
     * 
     * @param unknown $num_iid
     * @param unknown $qUrl
     */
    private function getUtao($id,$num_iid,$qUrl,$dx)
    {
    	$rUrl = 'http://uland.taobao.com/coupon/edetail?';
    	$qUrl=htmlspecialchars_decode($qUrl);
    	$geturl = parse_url($qUrl);
    	
    	$paramid = convertUrlQuery($geturl['query']);

    	$taodianjin = C('itk_taojindian_html');
    	if(strpos($taodianjin,'text/javascript')){
    		$pid = get_word($taodianjin,'pid: "','"');
    	}else{
    		$pid = $taodianjin;
    	}
    	//鹊桥推广
    	if($dx != 1 && C('itk_queqiao_pid')!=''){
    		$pid = C('itk_queqiao_pid');
    	}
    	
    	$reParam=array(
    		'itemId'=>$num_iid,
    		'activityId'=>$paramid['activityId'] == '' ? $paramid['activity_id']:$paramid['activityId'],
    		'pid'=>$pid,
			'src'=>'etk_niu',
    		'dx'=>1,
    	);
     	if($dx!=1){
			unset($reParam['dx']);
		}   	
    	$params = http_build_query($reParam);
    	$rUrl = $rUrl.$params;
    	// 是否开启自动转链接
    	if(C('itk_auto_privilege') ==1){
    		$rUrl = autoPrivilege($id,$num_iid , $paramid['activityId'] == '' ? $paramid['activity_id']:$paramid['activityId'] ,$rUrl);
    	}
    	$this->assign('hUrl',$rUrl);
    }
    
    public function ajaxUpItemDesc(){
    	if(!IS_AJAX) return;
    	$image=I('post.image');
    	$id=I('post.id');
    	$images='';
    	for($i=0;$i<count($image);$i++){
    		$images.=$image[$i];
    	}
    	$data['desc'] = $images;
    	$this->_mod->where(array('id' => $id))->save($data);
    }
}